package com.hdd.utils.wx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @author ;xuhu
 * @Date: 2020-11-06 16:04
**/
@Component
public class ActionRecordUtil {

    @Autowired
    private RedisUtil redisUtil;

    public final static String WX_SHARE_CIRCLE = "wx_share_circle";

    public final static String WX_SHARE_FRIEND = "wx_share_friend";

    public final static String WX_CLICK_REWARD = "wx_click_reward";

    /**
     * 获取key对应的记录值，并重置
     *
     * @param key 键值
     * @return
     */
    public Long resetRecordValue(String key){
        return recordValue(key, "reset");
    }

    /**
     * 将key对应的记录加一
     *
     * @param key
     * @return
     */
    public Long addRecordValue(String key){
        return recordValue(key, "add");
    }

    public Long getRecordValue(String key) {
        Object object = redisUtil.get(key);
        if (object != null) {
            return Long.parseLong(object.toString());
        }
        return 0L;
    }


    private synchronized Long recordValue(String key, String type) {
        long count = 0L;

        if ("reset".equals(type)) {
            Object num = redisUtil.get(key);
            redisUtil.set(key, count+"");
            if (num != null) {
                count = Long.parseLong(num.toString());
            }
        }else if ("add".equals(type)){
            Object num = redisUtil.get(key);
            if (num == null) {
                count = 1L;
            } else {
                count = Long.parseLong(num.toString()) + 1L;
            }
            redisUtil.set(key, count+"");
        }
        return count;
    }

}